import axios from 'axios'
import { Message} from 'element-ui';
import Bus from './bus'
let baseURL = 'http://127.0.0.1:7778'
const service = axios.create({
  baseURL,
  timeout: 50000
});

service.interceptors.request.use(config => {
   let token = localStorage.getItem("token");
   if(token===undefined||token===""||token===null){
    //  Message.error("请重新登录");
    //  window.location.href="/";
    Bus.$emit("index");
   }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  if(response.data.code === 200){
    return response.data;
  } else {
    Message({
        type: 'error',
        message: response.data.msg,
        showClose:true
    })
    return Promise.reject(response);
  }
}, error => {
  if (error && error.response) {
    const message = error.response.data.msg || "错误代码:"+error.response.status;
    Message({
      type: 'error',
      message,
      showClose:true
    })
    return Promise.reject(error.response)
  }
  if(error.config.url.indexOf('/status')!==-1||error.config.url.indexOf('/portlist')){
    Message({
      type: 'error',
      message: '未知错误,请重启软件试试',
      showClose:true
    })
  }
  return Promise.reject(error);
})
const get = function(url,params){
  const method = "GET";
  return service({
    url,
    method,
    params
  })
}

const post = function(url,data){
  const method = "POST";
  return service({
    url,
    method,
    data
  })
}
export default {
  get,
  post
}